package io.renren.service.impl;

import io.renren.dao.CustomBaseinfoDao;
import io.renren.entity.CustomBaseinfoEntity;
import io.renren.service.CustomBaseinfoService;
import io.renren.utils.FastJsonUtils;
import io.renren.utils.Global;
import io.renren.utils.HttpClientUtils;
import io.renren.utils.Sha1Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("customBaseinfoService")
public class CustomBaseinfoServiceImpl implements CustomBaseinfoService {

	/**
	 * 日志对象
	 */
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private CustomBaseinfoDao customBaseinfoDao;

	//新增页面下拉菜单名目
	private static String[] selectInfos = new String[]{"visit_style"};
	
	@Override
	public CustomBaseinfoEntity queryObject(String unitId){
		return customBaseinfoDao.queryObject(unitId);
	}
	
	@Override
	public List<CustomBaseinfoEntity> queryList(Map<String, Object> map){
		return customBaseinfoDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return customBaseinfoDao.queryTotal(map);
	}
	
	@Override
	public void save(CustomBaseinfoEntity customBaseinfo){
		String id = UUID.randomUUID().toString().replaceAll("-", "");
		customBaseinfo.setUnitId(id);
		customBaseinfoDao.save(customBaseinfo);
	}
	
	@Override
	public void update(CustomBaseinfoEntity customBaseinfo){
		customBaseinfoDao.update(customBaseinfo);
	}
	
	@Override
	public void delete(String unitId){
		customBaseinfoDao.delete(unitId);
	}
	
	@Override
	public void deleteBatch(String[] unitIds){
		customBaseinfoDao.deleteBatch(unitIds);
	}

	@Override
	@Transactional
	public void startSynToB1() throws Exception {
		logger.info("与b1进行数据同步开始");
		Map<String, Object> params = new HashMap<String, Object>();
		String key = Global.getConfig("b1key");// 获取key
		String url = Global.getConfig("b1url1");// 获取url
		logger.info("key:" + key);
		logger.info("url:" + url);

		String sign = Sha1Util.SHA1(params, key);// 计算签名
		logger.info("sign:" + sign);
		params.put("sign", sign);

		String result = HttpClientUtils.doPost(url, params);// 发送请求

		if (result != null) {
			result = result.replace("null", "''");
			Map<String, Object> b1Map = new HashMap<String, Object>();
			b1Map = FastJsonUtils.stringToCollect(result);
			if (b1Map != null && b1Map.size() > 0) {
				if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
					logger.info("data"+b1Map.get("data"));
					List<HashMap> dataList = FastJsonUtils.toList(String.valueOf(b1Map.get("data")), HashMap.class);
					//System.out.println("dataList.size:"+dataList.size());
					List<CustomBaseinfoEntity> addCustList = new ArrayList();
					if(dataList!=null&&dataList.size()>0){
						List<HashMap> addList = new ArrayList<HashMap>();
						List<HashMap> updateList = new ArrayList<HashMap>();
						List<HashMap> deleteList = new ArrayList<HashMap>();
						List<CustomBaseinfoEntity> custList= new ArrayList<CustomBaseinfoEntity>();
//						List<DepartmentTree> departmentList= new ArrayList<DepartmentTree>();
						StringBuffer idSb = new StringBuffer();
						String operteType = null;
						String b1Id = null;
						for(HashMap tMap:dataList){
							operteType = tMap.get("operteType").toString();// operteType 0：增加  1：更新  2：失效
							b1Id = tMap.get("cardCode").toString();
							if("0".equals(operteType)){
								addList.add(tMap);
							}else if("1".equals(operteType)){
								updateList.add(tMap);
							}else if("2".equals(operteType)){
								deleteList.add(tMap);
							}
							idSb.append(b1Id);
							idSb.append(",");
						}

						if(addList.size()>0){
							for(HashMap aMap:addList){
								CustomBaseinfoEntity  custTmp = new CustomBaseinfoEntity();
								Date now = new Date();
								custTmp.setCreateDate(now);
								custTmp.setDelFlag("0");
//								custTmp.setCreateBy(UserUtils.getUser());
								custTmp.setUnitAddress(String.valueOf(aMap.get("address")));
								custTmp.setUnitCode(String.valueOf(aMap.get("cardFname")));
								custTmp.setUnitId(String.valueOf(aMap.get("cardCode")));
								custTmp.setUnitName(String.valueOf(aMap.get("cardName")));
								custTmp.setLegalPerson(String.valueOf(aMap.get("phone1")));
								custTmp.setUnitTel(String.valueOf(aMap.get("phone2")));
								custTmp.setUnitNature(String.valueOf(aMap.get("u_dwxz")));
								custList.add(custTmp);

//								departmentList.add(departmentTreeService.inseDepar(aMap));
							}

							logger.info("批量保存数据开始");
							//saveBatch(custList);
							customBaseinfoDao.saveBatch(custList);
//							departmentTreeDao.saveBatch(departmentList);
							addCustList.addAll(custList);
							logger.info("批量保存数据完成");
							//logger.info("同步完成");

						}

						if(updateList.size()>0){
							custList= new ArrayList<CustomBaseinfoEntity>();
//							departmentList= new ArrayList<DepartmentTree>();
							for(HashMap uMap:updateList){
								CustomBaseinfoEntity  custTmp = new CustomBaseinfoEntity();
//								Date now = new Date();
//								custTmp.setSynTime(now);
//								custTmp.setUpdateDate(now);
								//custTmp.setDelFlag("0");
								//custTmp.setCreateBy(UserUtils.getUser());
								custTmp.setUnitAddress(String.valueOf(uMap.get("address")));
								custTmp.setUnitCode(String.valueOf(uMap.get("cardFname")));
								custTmp.setUnitId(String.valueOf(uMap.get("cardCode")));
								custTmp.setUnitName(String.valueOf(uMap.get("cardName")));
								custTmp.setLegalPerson(String.valueOf(uMap.get("phone1")));
								custTmp.setUnitTel(String.valueOf(uMap.get("phone2")));
								custTmp.setUnitNature(String.valueOf(uMap.get("u_dwxz")));
								custList.add(custTmp);
//								departmentList.add(departmentTreeService.inseDepar(uMap));

							}
							logger.info("批量更新数据开始");
							//updateBatch(custList);
							customBaseinfoDao.updateBatch(custList);
//							departmentTreeDao.updateBatch(departmentList);
							logger.info("批量更新数据完成");
							//logger.info("同步完成");

						}

						if(deleteList.size()>0){
							custList= new ArrayList<CustomBaseinfoEntity>();
							for(HashMap dMap:deleteList){
								CustomBaseinfoEntity  custTmp = new CustomBaseinfoEntity();
//								Date now = new Date();
								custTmp.setUnitId(String.valueOf(dMap.get("cardCode")));
								custList.add(custTmp);
//								departmentList.add(departmentTreeService.inseDepar(dMap));

							}
							logger.info("批量删除数据开始");
							//deleteBatch(custList);
							customBaseinfoDao.deleteBatchByList(custList);
//							departmentTreeDao.delteBylogicBatch(departmentList);

							logger.info("批量删除数据完成");
							//logger.info("同步完成");

						}
						/*if(1==1){
							throw new Exception();
						}*/
						//	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

						logger.info("开始更新b1库本次同步的所有记录的状态");
						String urlBack =  Global.getConfig("b1url2");// 获取url，已同步
						Map<String,Object> paramsBack = new HashMap<>();
						String b1Ids = idSb.toString();
						b1Ids = b1Ids.substring(0,b1Ids.lastIndexOf(","));
						paramsBack.put("cardCode",b1Ids );
						logger.info("b1Ids:"+b1Ids);
						String signBack = Sha1Util.SHA1(paramsBack, key);// 计算签名
						logger.info("signBack:" + signBack);
						paramsBack.put("sign", signBack);
						logger.info("urlBack:"+urlBack);
						String backResult = HttpClientUtils.doPost(urlBack, paramsBack);// 发送请求
						if (backResult != null) {
							Map<String, Object> b1BackMap = new HashMap<>();
							b1BackMap = FastJsonUtils.stringToCollect(backResult);
							if (!(b1BackMap.get("isSuc").equals("y"))) {
								if(addCustList.size()>0){
									logger.error("更新b1同步状态失败，删除本地本次新增记录");
									customBaseinfoDao.deleteBatchByList(addCustList);
								}
								throw new Exception();
							}
						}else{
							throw new Exception();
						}

						logger.info("客户基本信息同步完成");
					}else{
						logger.info("没有要更新数据，同步完成");
					}
				} else {
					throw new Exception();
				}
			}
		} else {
			throw new Exception();
		}




	}

	@Override
	public List<CustomBaseinfoEntity> getTree() {
		return customBaseinfoDao.getTree();
	}

	@Override
	public Map<String, Object> getListinfo() {
		Map<String, Object> map = new HashMap<>();
		for (String selectInfo : selectInfos) {
			map.put(selectInfo,customBaseinfoDao.getSelectInfo(selectInfo));
		}
		return map;
	}

}
